import datetime

from django.shortcuts import render, redirect

# Create your views here.
from App.forms import RegForm
from App.models import User
from django.http import HttpResponse

def index(request):
    return HttpResponse('Index')

def user(request):
    #cookie
    # username = request.COOKIES.get('username')
    # session
    username = request.session.get('username')

    return render(request, 'user.html', locals())


def logout(request):
    res = redirect('/user')

    # res.delete_cookie('username') # cookie
    #
    # clear 清空所有的session，但不会删除数据 flush清空并删除数据库 logout 清除并删除 del 删除某个
    # request.session.clear()
    request.session.flush()
    del request.session['username']
    return res


def login(request):
    if request.method == 'POST':
        info = request.POST.dict()
        info.pop('csrfmiddlewaretoken')
        print(info)
        user = User.objects.filter(username=info.get('username'), password=info.get('password')).first()
        # user = User.objects.filter(**info).first()
        if user:
            # 此处设置cookies
            response = redirect('/user') # 跳转首页
            # future = datetime.datetime.now() + datetime.timedelta(days=3)
            # response.set_cookie('username', user.username, expires=future)

            request.session['username'] = user.username
            request.session['id'] = user.id # 设置多个
            request.session.set_expiry(5) # 设置过期时间


            return response
        else:
            print('user error ')

    return render(request, 'login.html')


def check_login(func):
    def wrapper(*args, **kwargs):
        if args[0].COOKIES.get('username'):
            return func(*args, **kwargs)
        else:
            return redirect('/login')
    return wrapper

def do_register(request):
    username = request.POST.get('username')
    username = request.POST.get('username')


@check_login
def article_list(request):

    return HttpResponse('文章列表')


def login2(request):
    form_obj = RegForm()					# 用于get前请前段渲染标签
    if request.method == 'POST':
        form_obj = RegForm(request.POST)	                # request.POST内携带有前端ajax发送过来的验证码数据
        print(request.POST)
        if form_obj.is_valid():				        # 直接使用form校验，内部自动校验验证码是否正确
            print(form_obj.cleaned_data)
            pass	                  # 就不做登录逻辑处理了
        else:
            print(form_obj.errors)

    return render(request, 'login2.html',locals())
